package com.example.guiguiapplicatio.fragment.home;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.GetdataResponseBody.getsigningidendtimeApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.GetSigningendCallback;
import com.example.guiguiapplicatio.api.RecordDetailApi;
import com.example.guiguiapplicatio.api.getServicepackApi;
import com.example.guiguiapplicatio.DataManager.SelectServicePackageData;
import com.example.guiguiapplicatio.NewFileNextActivity;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.ServicePackageResponse;
import com.example.guiguiapplicatio.Response.Signing;
import com.example.guiguiapplicatio.databinding.FragmentServiceBinding;
import com.example.guiguiapplicatio.fragment.home.adapter.ServicepacksListAdapter;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NewFileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewFileFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private SelectServicePackageData selectServicePackageData;
    private List<ServicePackageResponse> packageResponseList;
    FragmentServiceBinding binding;

    // TODO: Rename and change types of parameters
    private String  et_id;
    private String endtime;
    private String mParam2;
    private int DataCode = 200;
    DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
    DateFormat df2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    Date date1 = null;
    Date date2 = null;
    private String startSigningDatetv;
    private String endSigningDatetv;
    private int year, month, day, hour, minute;
    private getServicepackApi getServicepackapi;
    private RecordDetailApi recordDetailApi;

    private RecordDetailApi recordDetailApi2;
    private getsigningidendtimeApi getsigningidendtimeApi;
    private ServicepacksListAdapter ServicepacksListadapter;
    private StringBuffer date, time;
    EditText NameeditText;
    EditText telephoneeditText;
    EditText textEthnicEditText;
    EditText textSexEditText;
    EditText etbirthDataEditText;

    public NewFileFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewFileFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NewFileFragment newInstance(String param1, String param2) {
        NewFileFragment fragment = new NewFileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_new_file, container, false);

        date = new StringBuffer();
        time = new StringBuffer();
        LinearLayout ll_startSigningDate = root.findViewById(R.id.ll_startSigningDate);
        TextView tv_startSigningDate = root.findViewById(R.id.tv_startSigningDate);
        LinearLayout ll_endSigningDate = root.findViewById(R.id.ll_endSigningDate);
        TextView tv_endSigningDate = root.findViewById(R.id.tv_endSigningDate);
        NameeditText = root.findViewById(R.id.et_name);
        telephoneeditText = root.findViewById(R.id.et_telephone);
        textEthnicEditText = root.findViewById(R.id.et_ethnic);
        textSexEditText = root.findViewById(R.id.et_sex);
        etbirthDataEditText = root.findViewById(R.id.et_birthData);
        ll_startSigningDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (date.length() > 0) { //清除上次记录的日期
                            date.delete(0, date.length());
                        }
                        tv_startSigningDate.setText(date.append(String.valueOf(year)).append("年").append(String.valueOf(month)).append("月").append(day).append("日"));
                        startSigningDatetv = tv_startSigningDate.getText().toString();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                final AlertDialog dialog = builder.create();
                View dialogView = View.inflate(getActivity(), R.layout.dialog_date, null);
                final DatePicker datePicker = dialogView.findViewById(R.id.datePicker);

                dialog.setTitle("设置日期");
                dialog.setView(dialogView);
                dialog.show();
                //初始化日期监听事件
                datePicker.init(year, month - 1, day, new DatePicker.OnDateChangedListener() {
                    @Override
                    public void onDateChanged(DatePicker view, int newYear, int monthOfYear, int dayOfMonth) {
                        year = datePicker.getYear();
                        month = datePicker.getMonth() + 1; // Month is 0-indexed, so add 1
                        day = datePicker.getDayOfMonth();
                    }
                });
            }
        });
        ll_endSigningDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (date.length() > 0) { //清除上次记录的日期
                            date.delete(0, date.length());
                        }
                        tv_endSigningDate.setText(date.append(String.valueOf(year)).append("年").append(String.valueOf(month)).append("月").append(day).append("日"));
                        endSigningDatetv = tv_endSigningDate.getText().toString();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                final AlertDialog dialog = builder.create();
                View dialogView = View.inflate(getActivity(), R.layout.dialog_date, null);
                final DatePicker datePicker = dialogView.findViewById(R.id.datePicker);
                dialog.setTitle("设置日期");
                dialog.setView(dialogView);
                dialog.show();
                //初始化日期监听事件
                datePicker.init(year, month - 1, day, new DatePicker.OnDateChangedListener() {
                    @Override
                    public void onDateChanged(DatePicker view, int newYear, int monthOfYear, int dayOfMonth) {
                        year = datePicker.getYear();
                        month = datePicker.getMonth() + 1; // Month is 0-indexed, so add 1
                        day = datePicker.getDayOfMonth();
                    }
                });
            }
        });
        initDateTime();
        Button btnSelectServicePackage = root.findViewById(R.id.btnSelectBasicServicePackage);
        btnSelectServicePackage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Show a dialog or start a new activity for selecting the service package
                showServicePackageSelectionDialog();
            }
        });
        Button btnNext = root.findViewById(R.id.confirm_the_contract);
        Button btnGetData = root.findViewById(R.id.get_data);
        EditText IdeditText = root.findViewById(R.id.et_id);
        recordDetailApi = new RecordDetailApi();
        recordDetailApi2 = new RecordDetailApi();
        recordDetailApi.setallCallback(recordCallback);
        recordDetailApi2.setallCallback(recordCallback2);
        getsigningidendtimeApi = new getsigningidendtimeApi();
        getsigningidendtimeApi.setallCallback(signingCallback);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(IdeditText.getText().toString().isEmpty()){
                    Toast.makeText(getActivity(), "请输入身份证号", Toast.LENGTH_LONG).show();
                }
                else {
                    recordDetailApi.performRecordDetailMain(IdeditText.getText().toString());
                }
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_id = IdeditText.getText().toString();
                if(et_id.isEmpty()){
                    Toast.makeText(getActivity(), "请输入身份证号", Toast.LENGTH_LONG).show();
                }
                else {
                    recordDetailApi2.performRecordDetailMain(IdeditText.getText().toString());
                }
            }
        });
        ImageButton ReteturnimageButton = root.findViewById(R.id.servic_back);
        ReteturnimageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.action_newFileFragment_to_navigation_home);
            }
        });
        return root;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }

    private void initDateTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
        hour = calendar.get(Calendar.HOUR);
        minute = calendar.get(Calendar.MINUTE);
    }

    /**
     * 日期改变的监听事件
     *
     * @param view
     * @param year
     * @param monthOfYear
     * @param dayOfMonth
     */

    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        this.year = year;
        this.month = monthOfYear;
        this.day = dayOfMonth;
    }

    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        this.hour = hourOfDay;
        this.minute = minute;
    }

    private void showServicePackageSelectionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("选择服务包");

        // Inflate a layout for the dialog
        View dialogView = View.inflate(getActivity(), R.layout.dialog_service_package, null);

        // Customize the dialog view and add your service package selection logic here
        RecyclerView recyclerView = dialogView.findViewById(R.id.service_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);// 替换成你的RecyclerView的ID
        ServicepacksListadapter = new ServicepacksListAdapter(new ArrayList<>());
        recyclerView.setAdapter(ServicepacksListadapter);
        selectServicePackageData = new SelectServicePackageData(ServicepacksListadapter);
        getServicepackapi = new getServicepackApi();
        getServicepackapi.setallCallback(selectServicePackageData);
        getServicepackapi.getServicepack();
// 通知适配器刷新数据
        builder.setView(dialogView);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Handle the selection and update the UI accordingly
                // For example, update a TextView with the selected service package name and content
                packageResponseList = selectServicePackageData.getSelectedItems();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }


    AllCallback recordCallback = new AllCallback() {
        @Override
        public void onSuccess(ResponseBody<Object> responseBody) {
            if (responseBody != null && responseBody.getData() != null) {
                // 解析JSON字符串为JsonObject
                JsonObject jsonObject = JsonParser.parseString(responseBody.getData().toString()).getAsJsonObject();
                String name = jsonObject.get("name").getAsString();
                String sex = jsonObject.get("sex").getAsString();
                String nation = jsonObject.get("nation").getAsString();
                String phone = jsonObject.get("phone").getAsString();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 在这里更新 UI 视图
                        NameeditText.setText(name);
                        telephoneeditText.setText(phone);
                        textEthnicEditText.setText(nation);
                        textSexEditText.setText(sex);
//                    etbirthDataEditText.setText();
                    }
                });
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "建档身份证不存在", Toast.LENGTH_LONG).show();
                    }
                });
            }
        }

        @Override
        public void onFailure(String errorMessage) {
            // 处理记录失败的逻辑
        }
    };

    AllCallback recordCallback2 = new AllCallback() {
        @Override
        public void onSuccess(ResponseBody<Object> responseBody) {
            if (responseBody != null && responseBody.getData() != null) {
                getsigningidendtimeApi.performgetsigningidendtime(et_id);
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "建档身份证不存在", Toast.LENGTH_LONG).show();
                    }
                });
            }
        }

        @Override
        public void onFailure(String errorMessage) {
            // 处理记录失败的逻辑
        }
    };

    GetSigningendCallback signingCallback = new GetSigningendCallback() {
        @Override
        public void onSuccess(ResponseBody<Signing> responseBody) throws ParseException {
            if (responseBody != null && responseBody.getData() != null) {
                date2 = responseBody.getData().getEndtime();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Create a bundle to carry the data
                        Intent intent = new Intent(getActivity(), NewFileNextActivity.class);
                        Gson gson = new Gson();
                        String packageResponseListJson = gson.toJson(packageResponseList);
                        intent.putExtra("packageResponseList", packageResponseListJson);
                        String et_name = NameeditText.getText().toString();
                        String et_telephone = telephoneeditText.getText().toString();
                        try {
                            date1 = df.parse(startSigningDatetv);
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        if (date1.compareTo(date2) > 0) {
                            if (packageResponseList == null) {
                                Toast.makeText(getContext(), "服务包未选择", Toast.LENGTH_LONG).show();
                            } else {
                                PreferencesUtil.putString(requireContext(), "beneficiary_id", et_id);
                                PreferencesUtil.putString(requireContext(), "beneficiary_name", et_name);
                                PreferencesUtil.putString(requireContext(), "beneficiary_telephone", et_telephone);
                                PreferencesUtil.putString(requireContext(), "startSigningDate", startSigningDatetv);
                                PreferencesUtil.putString(requireContext(), "endSigningDate", endSigningDatetv);
                                startActivity(intent);
                            }
                        } else {
                            Toast.makeText(getContext(), "该时间段已签约", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Create a bundle to carry the data
                        Intent intent = new Intent(getActivity(), NewFileNextActivity.class);
                        Gson gson = new Gson();
                        String packageResponseListJson = gson.toJson(packageResponseList);
                        intent.putExtra("packageResponseList", packageResponseListJson);
                        String et_name = NameeditText.getText().toString();
                        String et_telephone = telephoneeditText.getText().toString();
                        if(startSigningDatetv == null || endSigningDatetv == null) {
                            Toast.makeText(getContext(), "未选择签约时间", Toast.LENGTH_LONG).show();
                        }
                        else {
                            if (packageResponseList == null) {
                                Toast.makeText(getContext(), "服务包未选择", Toast.LENGTH_LONG).show();
                            } else {
                                PreferencesUtil.putString(requireContext(), "beneficiary_id", et_id);
                                PreferencesUtil.putString(requireContext(), "beneficiary_name", et_name);
                                PreferencesUtil.putString(requireContext(), "beneficiary_telephone", et_telephone);
                                PreferencesUtil.putString(requireContext(), "startSigningDate", startSigningDatetv);
                                PreferencesUtil.putString(requireContext(), "endSigningDate", endSigningDatetv);
                                startActivity(intent);
                            }
                        }
                    }
                });
            }
        }

        @Override
        public void onFailure(String errorMessage) {
            // 处理签约失败的逻辑
        }
    };
}